import Vue from 'vue'
import Vuex from 'vuex'
import axios from "axios";

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 所有的任务列表
    list: [],
    inputValue: '',
    nextId: 5,
    viewKey:''
  },
  mutations: {
    initList(state, list) {
      state.list = list
    },
    setInputValue(state, value) {
      state.inputValue = value
    },
    // 添加列表项目
    addItem(state, value) {
      const obj = {
        id: state.nextId,
        info: state.inputValue.trim(),
        done: false
      }
      state.list.push(obj)
      state.nextId++
      state.inputValue = ''
    },
    delObjById(state,id){
      const delId = state.list.findIndex(x => x.id === id)
      state.list.splice(delId,1)

    },
    changeStatus(state,params){
      const i = state.list.findIndex(x =>
      x.id === params.id
      )
      state.list[i].done = params.status
    },
    cleanDone(state){
      // 要记住，处理完数据要把数据交回给原数组
      state.list= state.list.filter(x => x.done === false)
    },
    changeViewKey(state,key){
      state.viewKey = key
    }
  },
  actions: {
    getList(context) {
      axios.get('/public.json').then(({data}) => {
        context.commit('initList', data)
      })
    }
  },
  getters:{
    getUndone(state){
      const undoneNum = state.list.filter(x => x.done === false).length
      return undoneNum
    },
    showList(state){
      if(state.viewKey === 'all') return state.list
      if(state.viewKey === 'undone') return state.list.filter(x => x.done === false)
      if(state.viewKey === 'done') return state.list.filter(x => x.done === true)
    }
  },
  modules: {}
})
